package C30;

import C017.main;

/**
 * ClassName: C02_GetMax
 * Package: C30
 * Description:
 *
 * @Author BCXJ
 * @Create 2024/12/17 14:57
 * @Version 1.0
 * @Since 1.0
 */
public class C02_GetMax {
    public static void main(String[] args) {
        int n1 = 100;
        int n2 = -1;
        System.out.println(getMax(n1, n2));
        System.out.println(getMax2(n1, n2));

        int min = Integer.MIN_VALUE;
        int max = Integer.MAX_VALUE;
        System.out.println(getMax(min, max));
        System.out.println(getMax2(max, min));
        /*
        12
        12
        2147483647
        -2147483648
        */
    }

    /**
     * n 为0 / 1 返回其相反值(0 -> 1, 1 -> 0)
     * @param n
     * @return
     */
    public static int flip (int n) {
        return 1 ^ n;
    }

    /**
     * 返回符号位
     * @param num
     * @return 正数返回1， 负数返回0
     */
    public static int sign(int num) {
        return flip(num >>> 31); // 逻辑右移
    }

    public static int getMax2(int num1, int num2) {
        int mid = num1 - num2;
        int s1 = sign(mid);
        int s2 = flip(s1);
        return s1 * num1 + s2 * num2;
    }


    /**
     * 不基于比较获取最大值, 不能使用 > < ==, 不会有溢出问题的方案
     * @param num1
     * @param num2
     * @return
     */
    public static int getMax(int num1, int num2) {
        int mid = num1 - num2;
        int s1 = sign(mid);
        int s2 = sign(num1);
        int s3 = sign(num2);
        int isDiff = s2 ^ s3;
        int isSame = flip(isDiff);
        int returnA = isDiff * s2 + isSame * s1;
        int returnB = flip(returnA);
        return returnA * num1 + returnB * num2;
    }
}
